package com.uinnova.product.eam.workable.listener;

import com.alibaba.fastjson.JSON;
import com.uinnova.product.eam.workable.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.HistoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设置子任务发起需要的流程变量-单节点会签
 */
@Slf4j
@Service("setCounterSignAssignessChildProcessTaskVariableListener")
public class SetCounterSignAssignessChildProcessTaskVariableListener implements ExecutionListener {

    @Value("${generic.user.countersign.child.url}")
    private String genericUserUrl;
    @Autowired
    private transient HistoryService historyService;
    @Autowired
    private HttpUtil httpUtil;

    @Override
    public void notify(DelegateExecution execution) {
        String businessKey = execution.getProcessInstanceBusinessKey();
        List<String> users = getUsers(execution);
        List<String> childVariableList = new ArrayList<>();
        for (String persion : users) {
            String childBusinessKey = businessKey + "_CHILD_PRE_REVIEW_FINAL_EXPERT_SUB_" + persion;
            Map<String,Object> childVariable = new HashMap<>();
            childVariable.put("assignee", persion);
            childVariable.put("childBusinessKey", childBusinessKey);
            childVariableList.add(JSON.toJSONString(childVariable));
        }
        Map<String, Object> variables = execution.getVariables();
        variables.put("childVariableList", childVariableList);
        execution.setVariables(variables);
    }

    private List<String> getUsers(DelegateExecution execution) {
        //获取当前任务的id
        FlowElement currentFlowElement = execution.getCurrentFlowElement();
        String taskDefinitionId = currentFlowElement.getDocumentation();
        log.info("当前任务定义id：{}", taskDefinitionId);
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId())
                .singleResult();
        //获取流程定义id
        String processDefinitionId = historicProcessInstance.getProcessDefinitionKey();
        log.info("当前流程定义id：{}", processDefinitionId);
        //获取当前流程实例业务主键
        String processInstanceBusinessKey = execution.getProcessInstanceBusinessKey();
        log.info("当前流程业务主键：{}", processInstanceBusinessKey);
        String requestUrl = genericUserUrl+"?defKey="+processDefinitionId+"&businessKey="+processInstanceBusinessKey+"&taskKey="+taskDefinitionId;
        log.info("获取通用会签子流程审批用户请求的url:{}",requestUrl);
        List<String> userLoginCodes = httpUtil.get(requestUrl, List.class);
        if (CollectionUtils.isEmpty(userLoginCodes)) {
            log.error("预评审-终审获取为空");
            throw new RuntimeException("预评审-终审获取为空");
        }
        return userLoginCodes;
    }
}
